#qpy:quiet
#-*-coding:utf8;-*-
"""
This is a sample project which use SL4A UI Framework,
There is another Sample project: https://github.com/qpython-android/qpy-calcount
"""
import qpy
import androidhelper
import requests
import sys
import time
import threading

try:
    import urllib.request as ur
except:
    import urllib as ur
from qsl4ahelper.fullscreenwrapper2 import *

# droid = androidhelper.Android()

id_list = []


class MainScreen(Layout):
    def __init__(self, item_id, tag=None):
        super(MainScreen,self).__init__(str("""<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 android:id="@+id/root"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	android:background="#ff0E4200"
	android:orientation="vertical"
	xmlns:android="http://schemas.android.com/apk/res/android">
	<ImageView
		android:id="@+id/logo"
		android:layout_width="fill_parent"
		android:layout_height="0px"
		android:layout_weight="10"
	/>
	<LinearLayout
		android:layout_width="fill_parent"
		android:layout_height="600px"
		android:orientation="horizontal"
		android:layout_weight="20">

		<TextView
			android:layout_width="fill_parent"
			android:layout_height="fill_parent"
			android:textSize="5dp"
 		android:text="点击load收听"
			android:id="@+id/text_main"
			android:background="#761573"
			android:textColor="#ffffffff"
			android:layout_weight="10"
			android:gravity="center"
		/>
    </LinearLayout>

	<ListView
		android:id="@+id/data_list"
		android:layout_width="fill_parent"
		android:layout_height="0px"
		android:layout_weight="55"/>

	<LinearLayout
		android:layout_width="fill_parent"
		android:layout_height="10px"
		android:orientation="horizontal"
		android:layout_weight="8">
		<Button
			android:layout_width="fill_parent"
			android:layout_height="fill_parent"
			android:text="Load"
			android:id="@+id/but_load"
			android:textSize="8dp"
			android:background="#ffEFC802"
			android:textColor="#ffffffff"
			android:layout_weight="1"
			android:gravity="center"/>
			<Button
			android:layout_width="fill_parent"
			android:layout_height="fill_parent"
			android:text="播放"
			android:id="@+id/but_control"
			android:textSize="8dp"
			android:background="#f8A01F00"
			android:textColor="#ffffff00"
			android:layout_weight="1"
			android:gravity="center"/>
			<Button
			android:layout_width="fill_parent"
			android:layout_height="fill_parent"
			android:text="next"
			android:id="@+id/but_next"
			android:textSize="8dp"
			android:background="#f8A81F00"
			android:textColor="#ffffff00"
			android:layout_weight="1"
			android:gravity="center"/>
		<Button
			android:layout_width="fill_parent"
			android:layout_height="fill_parent"
			android:text="Exit"
			android:id="@+id/but_exit"
			android:textSize="8dp"
			android:background="#ff06AF00"
			android:textColor="#ffffffff"
			android:layout_weight="1"
			android:gravity="center"/>
	</LinearLayout>
</LinearLayout>
"""),"SL4AApp")
        canrun = False
        self.idx = 0
        self.speak_text_s = []
        self.status = 'pause'
        self.item_id = item_id
        self.tag = tag
        if item_id is None:
            return
        self.next_id = None
        self.droid = None
        # self.init()

    def on_show(self):
        self.views.but_exit.add_event(click_EventHandler(self.views.but_exit, self.exit))
        self.views.but_load.add_event(click_EventHandler(self.views.but_load, self.load))
        self.views.but_control.add_event(click_EventHandler(self.views.but_control, self.action))
        self.views.but_next.add_event(click_EventHandler(self.views.but_next, self.next))
        # self.speak()
        if self.item_id in id_list:
            self.exit(None, None)
            return
        id_list.append(self.item_id)
        # self.views.text_main.text = self.item_id + str(self.views.text_main.text) + ' # ' + str(self.tag)
        pass

    def on_close(self):
        pass
        
    def speak(s, self=None):
        if self is None:
            self = s
        max_try = 0
        droid = androidhelper.Android()
        while True:
            try:
                if len(self.speak_text_s) == 0:
                    time.sleep(2)
                    continue
                if self.status == 'next':
                    self.set_speak_text(self)
                    continue
                    
                if self.status == 'stop':
                    break
                    
                if self.status != 'play':
                    time.sleep(2)
                    continue
                if max_try < 0 or not droid.ttsIsSpeaking().result:
                    if self.idx >= len(self.speak_text_s):
                        self.set_speak_text(self)
                        print('continue next')
                        continue
                        # self.exit(None, None)
                        # break
                    if max_try < 0:
                        droid = androidhelper.Android()
                    droid.ttsSpeak(self.speak_text_s[self.idx])
                    print(self.idx, self.speak_text_s[self.idx])
                    show_text = self.speak_text_s[self.idx]
                    
                    if self.idx > 0:
                        show_text = self.speak_text_s[self.idx - 1] + '\n' + show_text
                    if self.idx + 1 < len(self.speak_text_s):
                        show_text = show_text + '\n' + self.speak_text_s[self.idx + 1]
                    # self.views.text_main.text = show_text
                    # t=threading.Thread(target=self.show_text,args=[self.speak_text_s[0] + str(self.idx + 1) + '/' + str(len(self.speak_text_s)) + '\n' + show_text],)
                    # t.start()
                    
                    droid.dialogCreateAlert(self.speak_text_s[0] + str(self.idx + 1) + '/' + str(len(self.speak_text_s)), show_text)
                    # droid.dialogSetNeutralButtonText('取消')
                    droid.dialogShow()
                    
                    self.idx += 1
                time.sleep(0.5)
                max_try = 0
                # print('sleep\t', self.idx, droid.ttsIsSpeaking())
            except (ConnectionAbortedError, BrokenPipeError, Exception) as e:
                # droid.dialogCreateAlert('error', str(e))
                # droid.dialogShow()
                f = open('error.log' + str(self.idx), mode='w')
                f.write(str(e))
                f.flush()
                f.close()
                max_try -= 1
                time.sleep(3)
                break
        
        # time.sleep(10)
        # FullScreenWrapper2App.close_layout()
        # canrun = True
        # self.exit(None, None)
        
    def action(self, view, dump):
        if self.status == 'pause':
            self.unpause()
        elif self.status == 'play':
            self.pause()
        else:
            self.unpause()
        
    def next(self, view, dump):
        self.status = 'next'
        self.droid.makeToast('准备下一章')
        
    def stop(self, view, dump):
        # self.idx = 0
        # self.speak_text_s.clear()
        self.status = 'stop'
        
    def pause(self):
        self.status = 'pause'
        # droid = FullScreenWrapper2App.get_android_instance()
        self.droid.makeToast('暂停中')
        self.views.text_main.text = '暂停中'
        self.views.but_control.text = '播放'
        	
    def unpause(s, self=None):
        if self is None:
            self = s
        
        self.status = 'play'
        # droid = FullScreenWrapper2App.get_android_instance()
        self.droid.makeToast('播放中')
        self.views.text_main.text = '播放中'
        self.views.but_control.text = '暂停'
        	
    def load(self, view, dummy):
        droid = androidhelper.Android()
        line = droid.dialogGetInput('输入阅读章节ID')
        item_id = line.result
        if item_id is None or item_id == '':
            return
        self.item_id = item_id
        if self.set_speak_text():
            t=threading.Thread(target=self.speak,args=(self,))
            t.start()
        
    def set_speak_text(s, self=None):
        if self is None:
            self = s
        
        if self.item_id is None or self.item_id == '':
            # self.views.text_main.text = str('很奇怪  ') + '$$'
            return False
        u = 'http://zjl.hmxingkong.com/n/novel/getItemContent?itemId='
        u += self.item_id
        r = requests.get(u)
        json_data = r.json()
        next_id = json_data['data']['novelItem']['nextId']
        title = json_data['data']['novelItem']['title']
        print(next_id)
        text = json_data['data']['content']
        text = text.replace('&nbsp;', ' ').replace('<br/>', '\n')
        text = text.replace('<br />', '\n')

        # print(title + '\t' + text)
        # self.views.text_main.text = self.item_id + '_' + title
        splits = text.split('。')
        for i in range(0, len(splits)):
            	splits[i] = splits[i] + '。'
        splits[len(splits) -1] = splits[len(splits) -1] + '本章完。'
        splits.insert(0, title)
        self.speak_text_s.clear()
        self.speak_text_s.extend(splits)
        self.idx = 0
        self.next_id = str(next_id)
        self.item_id = str(next_id)
        # item_id = str(next_id)
        # self.views.text_main.text = str(next_id)
        # self.unpause(self)
        self.status = 'play'
        return True
        
    def show_text(self, text, ot=None):
        self.views.text_main.text = str(text)

    def exit(self, view, dummy):
        droid = FullScreenWrapper2App.get_android_instance()
        droid.makeToast("Exit")
        self.stop(None, None)
        FullScreenWrapper2App.close_layout()
        sys.exit()
        
    def init(self):
        droid = androidhelper.Android()
        FullScreenWrapper2App.initialize(droid)
        FullScreenWrapper2App.show_layout(self)
        self.droid = FullScreenWrapper2App.get_android_instance()
        
        if self.set_speak_text():
            t=threading.Thread(target=self.speak,args=(self,))
            t.start()
                
        FullScreenWrapper2App.eventloop()

in_id = None
canrun = True


if __name__ == '__main__':
    print('input item_id')
    # in_id = '358324'
    a = MainScreen(None, 'demo')
    if in_id is None: 
        droid = androidhelper.Android()
        line = droid.dialogGetInput('输入阅读章节ID')
        in_id = line.result
    a.item_id = in_id
    a.init()
        
    droid = androidhelper.Android()
    line = droid.dialogGetInput('程序结束')
